<template>
	<view class="container">
		<view class="status">蓝牙状态：{{ bleState }}</view>
		<view class="weight">实时体重：{{ realTimeWeight }} {{ unit }}</view>
		<button type="primary" @click="restart">重新扫描</button>
	</view>
</template>

<script>
	const {
		QNMPPlugin,
		QNConsts
	} = requirePlugin('QNBleApi')

	const APPID = 'wxf73463ef86a8e8ad' // 你的小程序 AppID

	export default {
		data() {
			return {
				bleApi: null,
				bleState: '未初始化',
				realTimeWeight: 0,
				unit: 'kg',
				connected: false,
				connecting: false,
				device: null
			}
		},
		onLoad() {
			// 初始化插件
			this.bleApi = new QNMPPlugin({
				appId: APPID, // ⚠️ 必须是小程序 appid
				mpwx: wx,
				logger: console
			})

			// 错误监听
			this.bleApi.onError = (err) => {
				console.error('捕捉到错误:', err.detail)
				this.bleState = '错误: ' + err.detail.desc
			}

			// SDK初始化完成回调
			this.bleApi.onReady = ({
				bleEnableState
			}) => {
				if (bleEnableState) {
					this.bleState = '蓝牙已开启，开始扫描设备'
					this.bleApi.startBleDeviceDiscovery()
				} else {
					this.bleState = '请先开启蓝牙'
				}
			}

			// 蓝牙事件监听
			this.bleApi.setBleEventListener({
				onBleDeviceFound: (device) => {
					if (!this.connecting && !this.connected) {
						console.log('发现设备:', device)
						this.connectDevice(device)
					}
				},
				onConnected: (device) => {
					this.bleState = '已连接'
					this.connected = true
					this.device = device
				},
				onDisconnected: () => {
					this.bleState = '设备已断开'
					this.connected = false
				}
			})

			this.bleApi.init()
		},
		methods: {
			async connectDevice(device) {
				this.connecting = true
				const user = {
					height: 170,
					gender: 1,
					birthday: '1995-01-01',
					isSport: false
				}
				try {
					await this.bleApi.createBleConnection(device, {
						onGetUnsteadyWeight: ({
							weight
						}) => {
							this.bleState = '测量中...'
							this.realTimeWeight = weight
						},
						onGetScaleData: ({
							measure
						}) => {
							this.bleState = '测量完成'
							console.log('测量数据:', measure)
						}
					}, {
						user,
						unit: 'kg'
					})
				} catch (e) {
					console.error('连接失败:', e)
					this.bleState = '连接失败'
				} finally {
					this.connecting = false
				}
			},
			async restart() {
				if (this.bleApi) {
					await this.bleApi.stop()
					this.connected = false
					this.bleApi.startBleDeviceDiscovery()
					this.bleState = '重新扫描中...'
				}
			}
		},
		onUnload() {
			if (this.bleApi) {
				this.bleApi.stop()
				this.bleApi.releaseBleSource()
			}
		}
	}
</script>

<style>
	.container {
		padding: 30rpx;
	}

	.status {
		margin-bottom: 20rpx;
		font-weight: bold;
	}

	.weight {
		margin-bottom: 20rpx;
		font-size: 32rpx;
	}
</style>